taxi = taxi || {};

taxi.GoogleMapsGeocoder = function(_utils) {
	this.utils = _utils;
	this.geocoder = new google.maps.Geocoder();
}

taxi.GoogleMapsGeocoder.prototype.resolveAddress = function( latLonAr, handler) {
	var latlon = this.utils.toLatLng(latLonAr);
	this.geocoder.geocode( {
		'latLng' : latlon
	}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			if (results[0]) {
				handler(results[0].formatted_address);
			}
		} else {
			console.debug("Geocoder failed due to " + status);
		}
	});
}

taxi.GoogleMapsGeocoder.prototype.consolidateAddress = function(
		addressString, context, handler) {
	if(context == null) context = {};
	var opts = {'address' : addressString};
	if(context.bounds){
		opts.bounds = this.utils.toBounds(context.boundaries);
	}
	if(context.location){
		var circle = new google.maps.Circle({center:this.utils.toLatLng(context.location),radius:taxi.CONTEXT_RADIUS});
		opts.bounds = circle.getBounds();
	}
	var self = this;
	var searchAddress = addressString;
	this.geocoder.geocode( opts, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			if (results.length > 0) {
				handler(new taxi.Address( {
					lat : results[0].geometry.location.lat(),
					lon : results[0].geometry.location.lng(),
					addressString : results[0].formatted_address
				}));
			} else {
				self.consolidateAddress(searchAddress,null,handler);
			}
		} else {
			//
		}
	});
}